package org.zoomdev.zoom.web.parameter.pre.impl;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.zoomdev.zoom.common.exceptions.ZoomException;
import org.zoomdev.zoom.web.action.ActionContext;
import org.zoomdev.zoom.web.parameter.PreParameter;
import org.zoomdev.zoom.web.parameter.PreParameterParser;
import org.zoomdev.zoom.web.utils.MediaType;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;

public final class UploadPreParamParser implements PreParameterParser {

    private static final DiskFileItemFactory factory = new DiskFileItemFactory();

    @Override
    public PreParameter preParse(ActionContext context) throws Exception {
        String contentType = context.getContentType();
        if (!MediaType.MULTIPART.is(contentType)) {
            return null;
        }

        HttpServletRequest request = context.getRequest();
        ServletFileUpload upload = new ServletFileUpload(factory);
        upload.setHeaderEncoding("UTF-8");
        try {
            List<FileItem> list = upload.parseRequest(request);
            HashMap<String, Object> data = new HashMap<>();
            for (FileItem item : list) {
                String name = item.getFieldName();
                if (item.isFormField()) {
                    String value = item.getString("UTF-8");
                    data.put(name, value);
                } else {
                    data.put(name, item);
                }
            }
            return new MapPreParameter(data);
        } catch (Exception e) {
            throw new ZoomException(e);
        }


    }

}
